
#include <linux/spi/spi.h>
#include <linux/of_gpio.h>
#include <linux/io.h>
#include <asm/io.h>

#include "spi.h"

/* spi 通信函数 */
int spi_writeCommand(struct spi_dev_node *dev, u8 cmd)
{
    u8 ret = 0;
    u8 data = 0;
    struct spi_transfer *t;
    struct spi_message m;
    struct spi_device *spi = (struct spi_device *)dev->private_data;

    t = kzalloc(sizeof(struct spi_transfer), GFP_KERNEL);
    gpio_set_value(dev->cs_gpio, 0); /* 片选拉低 */
    gpio_set_value(dev->dc_gpio, LCD_COMMAND);

    data = cmd;
    t->tx_buf = &data; /* 要发送的数据 */
    t->len = 1; /* 1个字节 */
    spi_message_init(&m); /* 初始化 spi_message */
    spi_message_add_tail(t, &m);/* 将 spi_transfer添加到 spi_message */
    ret = spi_sync(spi, &m); /* 同步发送 */
    
    kfree(t); /* 释放内存 */
    gpio_set_value(dev->cs_gpio, 1);/* 片选拉高，释放 ICM20608 */
    gpio_set_value(dev->dc_gpio, LCD_DATA);
    return ret;
}
EXPORT_SYMBOL(spi_writeCommand);

int spi_writeData(struct spi_dev_node *dev, u8 *buf, u8 len)
{
    u8 ret = 0;
    struct spi_transfer *t;
    struct spi_message m;
    struct spi_device *spi = (struct spi_device *)dev->private_data;

    t = kzalloc(sizeof(struct spi_transfer), GFP_KERNEL);
    gpio_set_value(dev->cs_gpio, 0); /* 片选拉低 */

    /* 发送要写入的数据 */
    t->tx_buf = buf; /* 要写入的数据 */
    t->len = len; /* 写入的字节数 */
    spi_message_init(&m); /* 初始化 spi_message */
    spi_message_add_tail(t, &m);/* 将 spi_transfer添加到 spi_message */
    ret = spi_sync(spi, &m); /* 同步发送 */

    kfree(t); /* 释放内存 */
    gpio_set_value(dev->cs_gpio, 1);/* 片选拉高，释放 ICM20608 */
    return ret;
}
EXPORT_SYMBOL(spi_writeData);

int spi_read_reg(struct spi_dev_node *dev, u8 reg)
{
    u8 ret = 0;
    unsigned int data = 0;

    ret = regmap_read(dev->regmap, reg, &data);
    return (u8)data;
}
EXPORT_SYMBOL(spi_read_reg);

void spi_write_reg(struct spi_dev_node *dev, u8 reg, u8 data)
{
    u8 ret = 0;

    ret = regmap_write(dev->regmap, reg, data);
}
EXPORT_SYMBOL(spi_write_reg);

MODULE_LICENSE("GPL");
MODULE_AUTHOR("xue");


